package com.ai.platform.spider.core;

import com.ai.platform.spider.logger.Logger;
import com.ai.platform.spider.logger.LoggerFactory;

import java.util.concurrent.CountDownLatch;

/**
 * 功能描述 一个爬虫引擎可以包含多个爬虫，每个爬虫可以认为是一个单独线程
 * 创建者 yeyingsheng
 * 创建时间 2018年06月22日
 */
public class Spider implements Runnable {

    private Logger logger = LoggerFactory.getLogger(Spider.class);

    private CountDownLatch pauseCountDown;

    private volatile boolean stop;

    private volatile boolean pause;

    private SpiderEngine spiderEngine;

    public Spider(SpiderEngine spiderEngine) {
        this.spiderEngine = spiderEngine;
        this.pause = false;
        this.stop = false;
    }

    @Override
    public void run() {
        logger.info(Thread.currentThread().getName());
        while (true) {
            if (stop) {
                //通知爬虫引擎结束
                spiderEngine.notifyComplete();
                break;
            }
            //暂停抓取
            if (pause) {
                try {
                    this.pauseCountDown.await();
                } catch (InterruptedException e) {
                    logger.error("can't pause : ", e);
                }
            }
            boolean start = false;

            //抓取间隔
            interval();
            //开始地址放入队尾重新抓取
            if (start && spiderEngine.isLoop()) {

            }
            stop=true;
        }
    }

    private void interval() {
        int interval = spiderEngine.getInterval();
        if (interval > 0) {
            try {
                Thread.sleep(randomInterval(interval));
            } catch (InterruptedException e) {
            }
        }
    }


    /**
     * 暂停，当前正在抓取的请求会继续抓取完成，之后会等到restart的调用才继续抓取
     */
    public void pause() {
        this.pauseCountDown = new CountDownLatch(1);
        this.pause = true;
    }


    /**
     * 重新开始
     */
    public void restart() {
        this.pauseCountDown.countDown();
        this.pause = false;
    }

    /**
     * 停止抓取
     */
    public void stop() {
        this.stop = true;
    }

    /**
     * 间隔时间在左右1s的范围内随机
     *
     * @param interval
     * @return
     */
    private int randomInterval(int interval) {
        int min = interval - 1000;
        min = min < 1 ? 1 : min;
        int max = interval + 1000;
        return (int) Math.rint(Math.random() * (max - min) + min);
    }


}
